import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/res/colors.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:oktoast/oktoast.dart';
// import 'package:visitor_scan_package/res/color_res.dart';

import '../../viewmodel/patrol/patrol_nfc_write_view_model.dart';

class PatrolWriteHomePage extends BaseStatefulMvvmWidget {
  @override
  State<StatefulWidget> createState() => _PatrolWriteHomeState();
}

class _PatrolWriteHomeState extends BaseMvvmState<CommonViewModel,PatrolWriteHomePage> {


  var model = PatrolModel();
  num unWriteNumber = 0;
  num hasWriteNumber = 0;

  var items = [
    PickerDataWithIdModel(pickName: '未写入', pickId: '0'),
    PickerDataWithIdModel(pickName: '已写入', pickId: '1')
  ];


  Future<void> _getNumberInfo() async {
     try{
       var data = await model.getPatrolNum();
       setState(() {
         unWriteNumber = (data["data"]['unWriteNum']??0);
         hasWriteNumber = (data["data"]['writeNum']??0);
       });
     }catch(e){
       print(e);
     }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getNumberInfo();
  }

  @override
  Widget buildLoadingContentView() {
   return Container();
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text("巡防点"),
      ),
      body: DefaultTabController(
        child: Column(
          children: [
            TabBar(
                tabs: items
                    .map((e) => Tab(
                  child: Stack(
                    children: [
                      Text(e.name).addToContainer(
                          padding:
                          EdgeInsets.symmetric(horizontal: 20)),
                      if((e.pickId=="0"?unWriteNumber:hasWriteNumber)!=0)
                      Text(
                        "${e.pickId=="0"?unWriteNumber:hasWriteNumber}",
                        style: TextStyle(
                            color: Colors.white, fontSize: 13),
                      )
                          .addToContainer(
                          decoration: BoxDecoration(
                              borderRadius: 10.borderRadius,
                              color: Colors.red),
                          alignment: Alignment.center,
                          padding: EdgeInsets.all(3),
                          constraints:
                          BoxConstraints(minWidth: 20),
                          height: 20)
                          .setLocation(right: 0)
                    ],
                  ),
                ))
                    .toList(),
                indicatorSize: TabBarIndicatorSize.label,
                labelColor: Colours.app_main,
                labelStyle: TextStyle(fontSize: 16),
                indicatorColor: Colours.app_main,
                unselectedLabelColor: Colors.grey)
                .addToContainer(color: Colors.white),
            TabBarView(
                children:
                items.map((e) => PatrolNfcWritePage(e.pickId!)).toList())
                .setWeight(1)
          ],
        ),
        length: items.length,
      ),
    );
  }

  @override
  CommonViewModel createViewModel() {
    return CommonViewModel(context);
  }

  @override
  void onRetryClick() {

  }
}

class PatrolNfcWritePage extends BaseStatefulMvvmWidget {
  final String isWrite;

  PatrolNfcWritePage(this.isWrite);

  @override
  State<StatefulWidget> createState() => _PatrolNfcWriteState();
}

class _PatrolNfcWriteState
    extends BaseMvvmListState<PatrolNfcWriteViewModel, PatrolNfcWritePage> {
  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Column(
      children: [
        Row(
          children: [
            Icon(Icons.search),
            CommonInput(
              hintText: '输入名称搜索',
              isDense: true,
              padding: EdgeInsets.zero,
              border: InputBorder.none,
              textInputAction: TextInputAction.search,
              onChanged: (str) {
                viewModel.keyword = str;
              },
              onSubmitted: (str) {
                viewModel.requestRefresh();
              },
            ).setWeight(1)
          ],
        ).addToContainer(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: 20.borderRadius)),
        loadingContentWidget.setWeight(1)
      ],
    );
  }

  @override
  Widget createItemWidget(int index) {
    var item = viewModel.listItems[index];
    return Row(
      children: [
        CommonText(item.name).setWeight(1),
        CommonText(1 == item.isWrite ? '写入成功' : '写入标签',
                textSize: 14,
                textColor: 1 == item.isWrite ? Colors.green : Colours.app_main)
            .onTap(() async {
          var nfcEnable = await NfcManager.instance.isAvailable();
          if (!nfcEnable) {
            showToast("nfc不可用");
            return;
          }
          showCupertinoDialog(
              context: context,
              barrierDismissible: false,
              builder: (context) {
                return CupertinoAlertDialog(
                  content: NfcTipContent(item.qrcode!, item.id.toString()),
                  actions: [
                    TextButton(
                        onPressed: () {
                          finish();
                        },
                        child: CommonText('关闭', textSize: 15))
                  ],
                );
              });
        })
      ],
    ).addToContainer(
        margin: EdgeInsets.symmetric(horizontal: 16),
        decoration:
            BoxDecoration(color: Colors.white, borderRadius: 10.borderRadius),
        padding: EdgeInsets.all(14));
  }

  @override
  PatrolNfcWriteViewModel createViewModel() {
    return PatrolNfcWriteViewModel(context, widget.isWrite);
  }

  @override
  void dispose() {
    eventBus.fire(SendMessageEvent(MessageConfig.RESTART_NFC));
    super.dispose();
  }

  @override
  EdgeInsets get listPadding => EdgeInsets.symmetric(vertical: 10);

  @override
  Widget get separatorDivider => Container(
        height: 10,
      );

  @override
  bool get canPullUp => true;
}

class NfcTipContent extends StatefulWidget {
  final String message;
  final String id;

  NfcTipContent(this.message, this.id);

  @override
  State<StatefulWidget> createState() => _NfcTipState();
}

class _NfcTipState extends State<NfcTipContent> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Icon(
          Icons.phone_android,
          color: Colors.blue[300],
        ),
        Container(
          height: 15,
        ),
        CommonText('靠近NFC标签')
      ],
    );
  }

  Future<void> initNfc() async {
    var nfcEnable = await NfcManager.instance.isAvailable();
    if (nfcEnable) {
      NfcManager.instance.startSession(
          onDiscovered: (NfcTag tag) async {
            Ndef? ndef = Ndef.from(tag);
            if (ndef == null || !ndef.isWritable) {
              NfcManager.instance.stopSession(errorMessage: "此标签不可写入");
              return;
            }
            var message = NdefMessage([NdefRecord.createText(widget.message)]);
            try {
              await ndef.write(message);
              updateStatus();
              showToast("写入成功");
              eventBus.fire(SendMessageEvent(MessageConfig.REFRESH_PATROL));
              //
              if (Platform.isIOS) {
                NfcManager.instance.stopSession(alertMessage: "写入成功");
              }
              Go().pop();
            } catch (e) {
              if (Platform.isIOS) {
                NfcManager.instance.stopSession(errorMessage: "写入失败：${e}");
              }
              return;
            }
          },
          alertMessage: "准备扫描，将标签贴近手机");
    }
  }

  var model = PatrolModel();

  Future<void> updateStatus() async {
    await model.updatePatrol(id: widget.id, isWrite: "1");
  }

  @override
  void initState() {
    super.initState();
    initNfc();
  }

  @override
  void dispose() {
    NfcManager.instance.stopSession();
    eventBus.fire(SendMessageEvent(MessageConfig.RESTART_NFC));
    super.dispose();
  }
}
